from odoo import api, models, fields, _
from odoo.exceptions import ValidationError
from odoo.tools.float_utils import float_compare
import logging
_logger = logging.getLogger(__name__)

class WorkorderDoneLineQty(models.TransientModel):
    _inherit = 'workorder.done.line.qty'

    def top_production(self, production):
        # 最顶层production
        ids = production._get_sources()
        parent_ids = [rec for rec in ids]
        if not parent_ids:
            origin = production
        else:
            production = parent_ids[0]
            while parent_ids:
                production = parent_ids.pop()
                ids = production._get_sources()
                parent_ids = [rec for rec in ids]
            origin = production
        return origin

    def done_move_qty(self):
        # 对外包采购 接收数量进行判断，工序总过数数量，不能超过采购总接收数量
        production = self.workorder_id.production_id
        hand_workorder = self._context.get('hand_workorder', False)
        if production.s_mes_lock and hand_workorder:
            raise ValidationError('当前工单已同步到MES系统，无法在odoo过数。')

        res = super().done_move_qty()

        top_production = self.top_production(self.workorder_id.production_id)
        if  self.workorder_id.state == 'done':
            top_production.s_is_workorder = True
        return res
